package cn.lisens.listener;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomServletContextListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(CustomServletContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("ServletContext 初始化完成");
        ServletContext servletContext = sce.getServletContext();
        
        // 设置应用属性
        servletContext.setAttribute("appStartTime", System.currentTimeMillis());
        servletContext.setAttribute("appVersion", "1.0.0");
        
        logger.info("应用启动时间: {}", new Date(System.currentTimeMillis()));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("ServletContext 即将销毁");
        ServletContext servletContext = sce.getServletContext();
        
        Long startTime = (Long) servletContext.getAttribute("appStartTime");
        if (startTime != null) {
            long uptime = System.currentTimeMillis() - startTime;
            logger.info("应用运行时长: {} 秒", uptime / 1000);
        }
    }
}
